package avicit.bdp.dds.server.log;


import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.remote.NettyRemotingServer;
import avicit.bdp.dds.remote.command.CommandType;
import avicit.bdp.dds.remote.config.NettyServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  logger server
 */
public class LoggerServer {

    private static  final Logger logger = LoggerFactory.getLogger(LoggerServer.class);

    /**
     *  netty server
     */
    private final NettyRemotingServer server;

    /**
     *  netty server config
     */
    private final NettyServerConfig serverConfig;

    /**
     *  loggger request processor
     */
    private final LoggerRequestProcessor requestProcessor;

    public LoggerServer(){
        this.serverConfig = new NettyServerConfig();
        this.serverConfig.setListenPort(Constants.RPC_PORT);
        this.server = new NettyRemotingServer(serverConfig);
        this.requestProcessor = new LoggerRequestProcessor();
        this.server.registerProcessor(CommandType.GET_LOG_BYTES_REQUEST, requestProcessor, requestProcessor.getExecutor());
        this.server.registerProcessor(CommandType.ROLL_VIEW_LOG_REQUEST, requestProcessor, requestProcessor.getExecutor());
        this.server.registerProcessor(CommandType.VIEW_WHOLE_LOG_REQUEST, requestProcessor, requestProcessor.getExecutor());
        this.server.registerProcessor(CommandType.REMOVE_TAK_LOG_REQUEST, requestProcessor, requestProcessor.getExecutor());
    }

    /**
     * main launches the server from the command line.
     * @param args arguments
     */
    public static void main(String[] args)  {
        final LoggerServer server = new LoggerServer();
        server.start();
    }

    /**
     * server start
     */
    public void start()  {
        this.server.start();
        logger.info("logger server started, listening on port : {}" , Constants.RPC_PORT);
        Runtime.getRuntime().addShutdownHook(new Thread(LoggerServer.this::stop));
    }

    /**
     * stop
     */
    public void stop() {
        this.server.close();
        logger.info("logger server shut down");
    }

}
